package com.wdc.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wdc.entity.BookEntity;
import com.wdc.service.BookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/book")
@Slf4j
public class BookController {

    @Autowired
    private BookService bookService;

    @PostMapping("/save")
    public Boolean save(@RequestBody BookEntity book) {
        log.info("book : {}", book.toString());
        return bookService.saveOrUpdate(book);
    }

    @GetMapping("/page")
    public Page<BookEntity> findPage(@RequestParam Integer pageNum,
                                     @RequestParam Integer pageSize,
                                     @RequestParam(defaultValue = "") String bookName,
                                     @RequestParam(defaultValue = "") String bookId,
                                     @RequestParam(defaultValue = "") String author) {

        log.info("bookName = {}, bookId = {}, author = {}", bookName,bookId,author);
        QueryWrapper<BookEntity> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(bookName)) {
            queryWrapper.like("bookName", bookName);
        }

        if (StringUtils.isNotBlank(bookId)) {
            queryWrapper.like("bookId", bookId);
        }

        if (StringUtils.isNotBlank(author)) {
            queryWrapper.like("author", author);
        }
        queryWrapper.orderByDesc("id");
        return bookService.page(new Page<>(pageNum,pageSize),queryWrapper);
    }

    @DeleteMapping("/{id}")
    public Boolean delete(@PathVariable Integer id) {
        return bookService.removeById(id);
    }

    @PostMapping("/del/batch")
    public boolean deleteBatch(@RequestBody List<Integer> ids){
        return bookService.removeByIds(ids);
    }

    @GetMapping("/image")
    public List<BookEntity> selectAllBooks() {
        System.out.println("查看所有图书");
        return bookService.selectAll();
    }

    @GetMapping("/bookmsg/{id}")
    public BookEntity getBookById(@PathVariable Integer id) {
        log.info("bookId = {}", id);
        return bookService.getById(id);


    }




}
